package com.ln.point.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ln.adoms.action.BaseAction;
import com.ln.core.orm.PageData;
import com.ln.core.utils.EncryptUtils;
import com.ln.core.utils.WebUtils;
import com.ln.point.entity.PointMember;
import com.ln.point.service.PointMemberService;

@Controller
@RequestMapping("/point/member")
public class PointMemberAction extends BaseAction {
	@Resource
	private PointMemberService memberService;

	@RequestMapping("/list")
	public ModelMap list(HttpServletRequest request) {
		PageData<PointMember> pageData = new PageData<PointMember>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = memberService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping(value = "/new")
	public String addForm(Model model) {
		return "/point/member/input";
	}

	@RequestMapping(value = "/detail/{mobile}")
	public String detail(Model model, @PathVariable("mobile") String mobile) {
		PointMember member = memberService.find("mobile", mobile.trim().replaceAll(" ", ""));
		model.addAttribute("member", member);
		return "/point/member/detail";
	}

	@RequestMapping(value = "/edit/{id}")
	public String editForm(@PathVariable("id") Integer id, Model model) {
		PointMember member = memberService.find(id);
		model.addAttribute(member);
		return "/point/member/input";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(PointMember member) {
		if (member.isNew()) {
			String pwd = member.getPassword();
			pwd = EncryptUtils.md5(pwd);
			member.setPassword(pwd);
			memberService.save(member);
		} else {
			memberService.update(member);
		}

		return "redirect:/point/member/list";// 重定向
	}

	@RequestMapping(value = "/repeat")
	@ResponseBody
	public boolean repeat(String mobile) {
		try {
			List<PointMember> list = memberService.findList("mobile", mobile);
			if (list != null && !list.isEmpty()) {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id) {
		memberService.delete(id);
		return "redirect:/point/member/list";// 重定向
	}

}
